<template>
  <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1" v-model:file-list="fileList" ref="upload"
    :on-exceed="handleExceed">

    <el-icon>
      <Plus />
    </el-icon>

    <template #file="{ file }">
      <div>

        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">

          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <el-icon><zoom-in /></el-icon>
          </span>

          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
            <el-icon>
              <Delete />
            </el-icon>
          </span>

        </span>
      </div>
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible">

    <el-image style="width: 100%; height: 100%" :src="dialogImageUrl" fit="cover" />

</el-dialog>
</template>
<script lang="ts" setup>
import { ref, defineExpose } from 'vue'
import { genFileId } from 'element-plus'
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'

import type { UploadFile, UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const fileList = ref([])
const upload = ref<UploadInstance>()

const handleRemove = (file: UploadFile) => {
  fileList.value.splice(0, 1)
}

// 自动替换上一张

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}


const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

// 把数组暴露出去
defineExpose({ fileList, handleRemove })
</script>
